<?php
declare(strict_types=1);

namespace App\Controller\WsWorker;

use App\Component\RedisGroupSever;
use App\Component\RedisUserSever;
use App\Component\Server;
use Hyperf\Utils\Codec\Json;


class Close
{
    public static function closeRoom($fd, $room, $user)
    {
        $redisGroup = new RedisGroupSever();
        $redisGroup->quitRoom($room, $fd);
        $roomData = $redisGroup->getRoom($room);

        $msg = [
            "type"        => "quitRoom",
            "room"        => $room,
            "num"         => count($roomData),
            "client_name" => $user["name"],
            "client_img"  => $user["img"],
            "content"     => "退出了聊天室"
        ];

        Server::sendToAll(Json::encode($msg), $roomData);

    }

    public static function close($fd)
    {
        $redisUser = new RedisUserSever();
        $userId = $redisUser->getUserByFd($fd);
        if (!$userId) {
            return "";
        }
        $redisUser->delUserByFd($fd);
        $redisUser->delUserFD($fd, $userId);

        $redisGroup = new RedisGroupSever();
        $roomList   = $redisGroup->getUserRoomList($fd);

        $user  = json::decode($redisUser->getUserInfo($userId));
        foreach ($roomList as $room) {
            $redisGroup->quitRoom($room, $fd);
            static::closeRoom($fd, $room, $user);
        }
    }
}